<template>
  <div>
    <div class="toptitle">
      <div class="imagbos">
        <el-image
          class="imagelogin"
          style="width: 80px; height: 80px"
          :src="require('../assets/logo.png')"
        ></el-image>
      </div>
      <div class="fristbix">
        广视三信应急广播人员编码软件
        <div class="englishtitle">
          Guangshi Sanxin (Taizhou) Information Technology Co., Ltd
        </div>
      </div>
    </div>
    <div class="hello">
      <div class="leftcar">
        <div>
          <el-card class="box-card">
            <el-form
              ref="form"
              label-width="120px"
              :rules="rules"
              :model="form"
            >
              <el-form-item label="行政区划">
                <LocaAddress ref="locaaddress" @locationbox="locationbox" />
                <el-input
                  class="xingzhengaddress"
                  v-model="xingzhengaddressmore"
                  placeholder="请输入详细地址"
                ></el-input>
              </el-form-item>
              <el-form-item label="姓名" prop="originshebeiname">
                <el-input
                  class="topindex"
                  v-model="form.originshebeiname"
                  placeholder="请输入姓名"
                ></el-input>
              </el-form-item>

              <el-form-item label="机构" prop="zitypecode">
                <el-select
                  v-model="form.zitypecode"
                  class="topindex"
                  placeholder="请选择"
                  @change="changezitypecode"
                >
                  <el-option
                    v-for="item in institution"
                    :key="item.code"
                    :label="item.name"
                    :value="item.code"
                  >
                  </el-option>
                </el-select>
              </el-form-item>

              <!-- <el-form-item label="IP地址">
                  <el-input
                    class="topindex"
                    v-model="ipaddress"
                    placeholder="请输入IP地址"
                  ></el-input>
              </el-form-item> -->
            </el-form>

            <div class="butbox">
              <el-button type="success" @click="getlocatbox"
                >获取代编码</el-button
              >
              <el-button
                type="warning"
                @click="addserves"
                :disabled="!showboxdes"
              >
                保存</el-button
              >
              <el-button
                type="warning"
                @click="showdelog"
                :disabled="pagedate.length <= 0"
              >
                导出预览</el-button
              >
              <!-- @click="generateCSV" -->
              <!-- <el-button type="warning" @click="minilocation"
                >获取经纬度</el-button
              >  -->
              <el-button type="info" @click="reback">清空</el-button>
            </div>
          </el-card>
        </div>
        <div class="desbox">
          <el-descriptions class="margin-top" title=" " :column="1" border>
            <el-descriptions-item>
              <template slot="label">
                <i class="el-icon-user"></i>
                行政区域
              </template>
              {{ showboxdes ? locationaddres + xingzhengaddressmore : "" }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                <i class="el-icon-user"></i>
                姓名拼音
              </template>
              {{ pingyingname }}
            </el-descriptions-item>
            <!-- <el-descriptions-item>
              <template slot="label">
                <i class="el-icon-user"></i>
                机构编码
              </template>
              {{ form.zitypecode }}
      
            </el-descriptions-item> -->
            <el-descriptions-item>
              <template slot="label">
                <i class="el-icon-user"></i>
                人员编码
              </template>
              {{ lastbianma }}
            </el-descriptions-item>
            <!-- <el-descriptions-item>
              <template slot="label">
                <i class="el-icon-mobile-phone"></i>
                经纬度
              </template>
              {{ localng }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                <i class="el-icon-mobile-phone"></i>
                编码
              </template>
              {{ lastbianmaadd }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                <i class="el-icon-mobile-phone"></i>
                科通编码
              </template>
              {{ 'F'+lastbianma }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                <i class="el-icon-mobile-phone"></i>
                IP地址
              </template>
              {{ pingyingname }}
            </el-descriptions-item> -->
          </el-descriptions>
        </div>
      </div>
      <!-- <div class="mapboxs">
        <Mapbox ref="mapbox" @haslocationmap="haslocationmap" />
      </div> -->
      <el-dialog title="导出编码显示" :visible.sync="dialogVisible" width="85%">
        <div class="table">
          <div class="row row1">
            <div class="cell cell1">人员姓名</div>
            <!-- <div class="cell cell1">姓名拼音</div> -->
            <div class="cell cell1">行政区域</div>
            <div class="cell cell1">人员编码</div>
        
          </div>
          <div class="row" v-for="(item, index) in pagedate" :key="index">
            <div class="cell cell1">{{ item[0] }}</div>
            <div class="cell cell2">{{ item[1] }}</div>
            <div class="cell cell3">{{ item[2] }}</div> 
            <!-- <div class="cell cell3">{{ item[3] }}</div>  -->

            <div class="cell cell3">
              <el-button
                size="mini"
                type="warning"
                icon="el-icon-delete-solid"
                circle
                @click="deleteitem(index)"
              ></el-button>
            </div>
          </div>
        </div>
        <div>
          <el-button
            type="success"
            @click="generateCSV"
            :disabled="pagedate.length <= 0"
            >导出文档</el-button
          >
          <el-button type="info" @click="rebackwendang">清空导出</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
// import hanziToPinyin from 'hanzi-to-pinyin';
import LocaAddress from "./loaca-address.vue";
import ziyDate from "./ziyuan.json";
import institution from "./institution.json";
// import Mapbox from "./map-box.vue";
import pinyin from "pinyin";

// const XLSX = require('xlsx');
import Papa from "papaparse";
export default {
  name: "HelloWorld",
  data() {
    return {
      // hanziToPinyin,
      institution,
      locationaddres: "",
      xingzhengaddressmore: "",
      resourceLeveldate: "",
      community: "",
      otherziyuancode: "",
      lastbianma: "",
      lastbianmaadd: "",
      ipaddress: "",
      ziyuanshunxucode2: "",
      boxshowzitypeDate: "",
      showboxdes: false,
      formdate: {
        topname: "",
        topcode: "",
        scendname: "",
        scendcode: "",
        originshebeiname: "",
      },
      form: {
        resourceLeveldate: "",
        topcode: "",
        ziyuanshunxucode: "",
        ziyuanshunxucode2: "",
        zitypecode: "",
      },
      rules: {
        // resourceLeveldate: [
        //   { required: true, message: "请选择资源级别识别码", trigger: "blur" },
        // ],
        topcode: [
          { required: true, message: "请选择资源类型", trigger: "blur" },
        ],
        ziyuanshunxucode: [
          { required: true, message: "请填写资源类型顺序码", trigger: "blur" },
          { min: 2, max: 2, message: "长度为2位", trigger: "blur" },
        ],
        zitypecode: [
          { required: true, message: "请选择机构", trigger: "blur" },
        ],
        ziyuanshunxucode2: [
          // { required: true, message: "请填写资源类型顺序码", trigger: "blur" },
          { min: 2, max: 2, message: "长度为2位", trigger: "blur" },
        ],
      },
      dialogVisible: false,
      ziyuanshunxucode: "",
      zitypecode: "",
      showqitabox: false,
      ziyuan: [],
      pingyingname: undefined,
      scendziyuan: [],
      locationcode: "",
      ming: undefined,
      xing: undefined,
      localng: null,
      resourceLevel: [
        { code: "1", name: "中央级" },
        { code: "2", name: "省级" },
        { code: "3", name: "市级" },
        { code: "4", name: "县级" },
        { code: "5", name: "乡级" },
        { code: "6", name: "村级" },
      ],
      zitypeDate: [
        { code: "04", name: "终端" },
        { code: "01", name: "本级平台/系统/机构" },
        { code: "02", name: "应急广播适配器" },
        { code: "03", name: "传输覆盖播出设备" },
      ],
      pagedate: [],
    };
  },

  components: { LocaAddress },
  computed: {
    // zitypecode(){
    //   this.zitypeDate.find(item=>{
    //    if(item.code==this.form.zitypecode){
    //     return item.name
    //    }
    //   })
    // }
  },
  props: {
    // 街道数据
  },
  beforeDestroy() {
    window.removeEventListener("beforeunload", this.handleBeforeUnload);
  },
  mounted() {
    console.log("beforeunload");
  },
  created() {
    this.ziyuan = ziyDate;
    window.addEventListener("beforeunload", this.handleBeforeUnload);
  },

  methods: {
    addnames(firstname) {
      console.log(firstname)
      
      switch (firstname.length) {
        case 2:
          this.xing = "V" + firstname.substring(0, 1);
          this.ming = "V" + firstname.substring(1, 2);
          break;
          case 3:
          this.xing = "V" + firstname.substring(0, 1);
          this.ming = firstname.substring(1, 2);
          break;
          case 4:
          this.xing = firstname.substring(0, 2);
          this.ming = firstname.substring(1, 2);
          break;
          // default:

      }
    },

    getRandomint(){
      return Math.floor(Math.random() * 90) + 10;
    },
    convertedData(name) {
      return pinyin(name, { style: pinyin.STYLE_FIRST_LETTER }).join("");
    },

    handleBeforeUnload(event) {
      console.log(event);
      // 这里可以添加逻辑来决定是否要显示提示信息
      if (this.pagedate.length > 0) {
        const message = "你有未保存的更改，确定要离开吗？";
        event.returnValue = message; // 兼容性设置
        return message;
      }
    },
    showdelog() {
      this.dialogVisible = true;
    },
    addserves() {
      let addcode = JSON.stringify(this.lastbianma);
      let addboothe = false;
      console.log(addcode);
      this.pagedate.map((item) => {
        item[2] == addcode ? (addboothe = true) : (addboothe = false);
      });
      // this.getlocatbox()
      if (!addboothe) {
        this.pagedate.push([
          this.form.originshebeiname, 
          // this.pingyingname,
          this.locationaddres + this.xingzhengaddressmore, 
          JSON.stringify(this.lastbianma),
          addcode,
    
        ]);
      } else {
        // this.$message({
        //       type: 'info',
        //       message: ''
        //     });

        this.$alert("当前文档里已有相同数据,更改后添加", "提示", {
          confirmButtonText: "确定",
        });
      }

      this.showboxdes = false;
    },
    generateCSV() {
      const data = [
        [
          "人员姓名", 
          // "姓名拼音",
          "行政区域",  
          "人员编码",
      
        ],
        ...this.pagedate,
      ];

      const csv = Papa.unparse(data, {
        delimiter: ",", // CSV字段分隔符，默认为逗号
        newline: "\r\n", // 行分隔符，默认为CRLF（回车换行）
        encoding: "utf-8", // 字符编码，默认为UTF-8
      });
      const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
      const filename = "编码.csv";
      console.log(navigator);
      if (navigator.msSaveBlob) {
        // For IE 10+
        navigator.msSaveBlob(blob, filename);
      } else {
        // For other browsers
        const link = document.createElement("a");
        if (link.download !== undefined) {
          const url = URL.createObjectURL(blob);
          link.setAttribute("href", url);
          link.setAttribute("download", filename);
          link.style.visibility = "hidden";
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        }
      }
    },

    minilocation() {
      this.$refs.locaaddress.minilocation();
    },
    rebackwendang() {
      this.pagedate = [];
    },
    reback() {
      this.form = {
        resourceLeveldate: "",
        topcode: "",
        ziyuanshunxucode: "",
        zitypecode: "",
        ziyuanshunxucode2: "",
      };
      this.formdate = {
        topname: "",
        topcode: "",
        scendname: "",
        scendcode: "",
        originshebeiname: "",
      };
      this.ipaddress = "";
      this.ziyuanshunxucode2 = "";
      this.showqitabox = false;
      this.lastbianma = "";
      this.lastbianmaadd = "";
      this.localng = null;
      // this.$refs.mapbox.initAMap();
      this.$refs.locaaddress.reset();
      this.showboxdes = false;
      this.locationaddres = "";
      this.xingzhengaddressmore = "";
      this.community = "";

      this.ipaddress = "";
    },
    changezitypecode(e) {
      this.form.zitypecode = e;
      console.log(e);
      // let areaData = this.zitypeDate.filter((item) => item.code == e)[0].name;
      // console.log(areaData);
      // this.boxshowzitypeDate = areaData;
    },
    haslocationmap(data) {
      this.localng = data;
    },
    locationbox(date) {
      console.log(date);
      this.form.resourceLeveldate = date.toptopnub;
      this.locationcode = date.regionalNumber;
      // this.$refs.mapbox.getlocationname(date.name);
      this.locationaddres = date.name;
      this.community = date.community;
    },
    changeZiyuan(e) {
      this.scendziyuan = this.ziyuan.filter((item) => {
        return item.code == e;
      })[0].children;
      this.formdate.scendcode = "";
    },
    otherbox() {
      this.showqitabox = !this.showqitabox;
    },
    deleteitem(index) {
      this.pagedate.splice(index, 1);
    },
    getlocatbox() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.$refs.locaaddress.minilocation();
          this.addnames(this.convertedData(this.form.originshebeiname))
          this.pingyingname = this.convertedData(this.form.originshebeiname);
          this.showboxdes = true;
          let newscentdcode = "";
          if (this.showqitabox) {
            newscentdcode = this.otherziyuancode;
          } else {
            newscentdcode = this.formdate.scendcode;
          }
          // let lastbox =
          //   this.form.resourceLeveldate +
          //   this.boxalllnub(this.locationcode) +
          //   newscentdcode +
          //   this.boxtwonub(this.form.ziyuanshunxucode) +
          //   this.form.zitypecode +
          //   this.boxtwonub(this.form.ziyuanshunxucode2);
let quyubianma= this.boxalllnub(this.locationcode)
 
          this.lastbianma =this.xing+quyubianma.substring(0, 3)+
          this.getRandomint()+quyubianma.substring(3,6)+this.form.zitypecode +
          quyubianma.substring(6,8)+this.getRandomint()+quyubianma.substring(8,12)+ this.ming;
          this.lastbianmaadd =
            this.form.resourceLeveldate +
            "-" +
            this.boxalllnub(this.locationcode) +
            "-" +
            newscentdcode +
            "-" +
            this.boxtwonub(this.form.ziyuanshunxucode) +
            "-" +
            this.form.zitypecode +
            "-" +
            this.boxtwonub(this.form.ziyuanshunxucode2);
        }
      });
    },
    boxtwonub(nub) {
      if (nub.length < 2) {
        let zeronub = 2 - nub.length;
        let newnub = nub;
        for (let i = 0; i < zeronub; i++) {
          newnub = newnub + "0";
        }
        return newnub;
      } else {
        return nub;
      }
    },
    boxalllnub(nub) {
      // 未满13位加0
      if (nub.length < 12) {
        let zeronub = 12 - nub.length;
        let newnub = nub;
        for (let i = 0; i < zeronub; i++) {
          newnub = newnub + "0";
        }
        return newnub;
      } else {
        return nub;
      }
    },
  },
};
</script>

<style scoped>
h3 {
  margin: 40px 0 0;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  /* display: inline-block; */
  margin: 0 10px;
}

a {
  color: #42b983;
}

.butbox {
  margin: 25px 0;
  display: inline-block;
  text-align: left;
  width: 100%;
  text-indent: 120px;
}

.hello {
  display: flex;
  flex-direction: row;
}

.leftcar {
  width: calc(100% - 60px);
  margin-left: 30px;
}

.mapboxs {
  margin-left: 25px;
}

.topindex {
  width: 50%;
}

::v-deep .el-form-item__content {
  text-align: left !important;
}

.minselect {
  width: 190px;
  margin: 0 5px;
}

.litterbut {
  display: inline-block;
}

.othertext {
  margin: 0 15px;
}

.mintitle {
  line-height: 40px;
  letter-spacing: 2px;
}

.desbox {
  width: 80%;
  margin-top: 15px;
}

.toptitle {
  /* line-height:80px; */
  background: #050e41f6;
  margin-bottom: 15px;
  font-size: 30px;
  color: #fff;
  display: flex;
  padding: 10px 0;
  flex-direction: row;
  font-family: PangMenZhengDao;
  align-items: center;
  justify-content: center;
}
.imagbos {
  display: flex;
  justify-content: center;
}
.englishtitle {
  font-size: 18px;
  margin-top: 5px;
}

@font-face {
  font-family: "PangMenZhengDao";
  src: url("../assets/pmzd.ttf");
  font-weight: normal;
  font-style: normal;
}

.xingzhengaddress {
  width: 80%;
  margin-top: 18px;
  text-indent: 2px;
}

.fristbix {
  display: flex;
  text-align: center;
  flex-direction: column;
  align-items: center;
}

.imagelogin {
  margin-right: 15px;
}
.row {
  display: grid;
  grid-template-columns: 25% 25% 25% 25%;
  border: 1px solid;
  line-height: 36px;
  border-top: none;
}
.row.row1 {
  /* border-bottom: none; */
  border-top: 1px solid;
}
.cell {
  border-right: 1px solid;
}
.table {
  height: 500px;
  overflow-y: scroll;
}
.redtext {
  color: #f11f10;
}
.onrowlist {
  display: flex;
  flex-direction: row;
  .redtext {
    margin-left: 10px;
  }
}
</style>
